import { MODULE_SPLIT } from '@util/constants';
import { get, difference } from 'lodash';

/**
 * 针对组件授权检查
 * @param {*} user 用户
 * @param {*} module 模块,必填
 * @param {*} power 权限,选填,默认为全部,多个权限时采用|分割
 * @param {*} unAccessed 未授权时展示组件,选填,默认为null
 * @example
 * 1. access({module1: []},'module1',<span>unAccess</span>)(<span>被检验</span>)
 * 2. access({module1: []},'module1','view', <span>unAccess</span>)(<span>被检验</span>)
 * 3. access({module1: []},'mudule1','view')(<span>被检验</span>)
 */
const access = (user, module, power, unAccessed) => {
  const { access } = user;
  /* eslint-disable */
  // 默认具有查看权限
  if (!power) {
    power = 'view';
    unAccessed = null;
  }
  if (!unAccessed && typeof power !== 'string') {
    unAccessed = power;
    power = 'view';
  }
  power = power.split('|');
  /* eslint-disable */
  // personal|aaaa
  // personal|bbbb
  const modulePower = access.reduce((powers, current = {}) => {
    const { module: currentModuleStr, power: currentPower } = current;
    const currentModules = currentModuleStr.split(MODULE_SPLIT);
    if (get(currentModules, '0') === module) {
      return powers.concat(currentPower);
    }
    return powers;
  }, []);
  const canAccess = difference(power, modulePower).length === 0;

  return element => (canAccess ? element : unAccessed);
};

// 针对元素的权限模块检查单例
export default access;
